package com.example.shipload_e.activitys.discharge_feedback;

import java.lang.ref.WeakReference;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.DatePickerDialog;
import android.app.ProgressDialog;
import android.app.TimePickerDialog;
import android.app.DatePickerDialog.OnDateSetListener;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.text.method.NumberKeyListener;
import android.util.Log;
import android.view.KeyEvent;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.ViewGroup;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.example.shipload_e.R;
import com.example.shipload_e.ShipMentWelcomeActivity;
import com.example.shipload_e.activitys.shipment_feedback.ShipmentFinishFormActivity.MyAdapter;
import com.example.shipload_e.activitys.shipment_feedback.ShipmentFinishFormActivity.ViewHolder;
import com.example.shipload_e.album_tool.PublishedActivity;
import com.example.shipload_e.database_dao.DBUtil;
import com.example.shipload_e.huawei_push.MyApplication;
import com.example.shipload_e.service.BizNetworkService;
import com.example.shipload_e.util.HttpActConstant;
import com.example.shipload_e.util.HttpConstant;
import com.example.shipload_e.util.SharePreferenceUtil;
import com.example.shipload_e.util.SystemDateTools;

public class DischargeFinishFormActivity extends Activity {
	private ImageButton	              submit_button, uploadIb;
	private EditText	              datePickerEt, timePickerEt, actualLoadCountEt,
	        actualLoadUnitEt, actualLoadUnitEt2, lossCountEt, cargoCountEt;
	private ImageButton	              mGoback;
	private Button	                  countTabBt;

	ProgressDialog	                  progressDialog;
	private MyHandler	              handlers;
	private String	                  submitData	= "00";
	private String	                  submitTime	= "00";
	private ListView	              recordList;
	private List<Map<String, Object>>	mData;
	private boolean	                  hasDatas	 = false;
	DischargeFinishFormActivity	      THISAC	 = DischargeFinishFormActivity.this;
	SharePreferenceUtil	              spu;

	static class MyHandler extends Handler {
		WeakReference<DischargeFinishFormActivity>	tActivity;

		MyHandler(DischargeFinishFormActivity activity) {
			tActivity = new WeakReference<DischargeFinishFormActivity>(activity);
		}

		@Override
		public void handleMessage(Message msg) {
			DischargeFinishFormActivity theActivity = tActivity.get();
			Bundle data = msg.getData();
			if(!data.isEmpty()) {
				switch (msg.what) {
					case HttpActConstant.SUBMIT_ISCHARGE_FINISH_TASKS:
						theActivity.progressDialog.dismiss();
						if(HttpConstant.SUBMIT_SUCCESS.equals(data
						        .getString(HttpConstant.SUBMIT_SUCCESS))) {
							new Thread(new BizNetworkService(theActivity, new Handler(), HttpActConstant.INIT_DISCHARGE_FINISH_TASKS, null))
							        .start();
							theActivity.progressDialog.setMessage("正在更新列表...");
							theActivity.progressDialog.show();
						}
						Toast.makeText(theActivity, data.getString("msg"), Toast.LENGTH_SHORT)
						        .show();
						break;

					default:
						break;
				}
			} else {}
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.discharge_finish_edit_main);
		progressDialog = new ProgressDialog(THISAC);
		handlers = new MyHandler(THISAC);
		spu = new SharePreferenceUtil(THISAC);
		initView();
		initDatas();
		com.example.shipload_e.util.SysApplication.getInstance().addActivity(this);
	}

	private void initView() {
		countTabBt = (Button) findViewById(R.id.count_tab);
		JSONArray showCount = DBUtil.selectPhotoRespondByTaskId(THISAC, spu.getFollowId());
		countTabBt.setText(showCount.length() + "");
		String getUnit = getIntent().hasExtra("followUnit") == false ? "isNone" : getIntent()
		        .getStringExtra("followUnit");
		actualLoadUnitEt = (EditText) findViewById(R.id.actual_load_unit);
		actualLoadUnitEt.setText(getUnit);
		actualLoadUnitEt.setEnabled(false);
		actualLoadUnitEt2 = (EditText) findViewById(R.id.actual_load_unit2);
		actualLoadUnitEt2.setText(getUnit);
		actualLoadUnitEt2.setEnabled(false);
		actualLoadCountEt = (EditText) findViewById(R.id.actual_load_count);
		actualLoadCountEt.setInputType(InputType.TYPE_CLASS_PHONE);
		lossCountEt = (EditText) findViewById(R.id.loss_count);
		cargoCountEt = (EditText) findViewById(R.id.cargo_count);
		cargoCountEt.setEnabled(false);
		actualLoadCountEt.setKeyListener(nkl);
		actualLoadCountEt.addTextChangedListener(watcher);
		lossCountEt.setKeyListener(nkl);
		mGoback = (ImageButton) findViewById(R.id.m_goback);
		submit_button = (ImageButton) findViewById(R.id.submit_button);
		mGoback.setOnClickListener(ocl);
		submit_button.setOnClickListener(ocl);

		datePickerEt = (EditText) findViewById(R.id.date_picker);
		timePickerEt = (EditText) findViewById(R.id.time_picker);
		datePickerEt.setText(SystemDateTools.getDateByNowByType("yyyy年MM月dd日"));
		timePickerEt.setText(SystemDateTools.getDateByNowByType("HH时mm分"));
		datePickerEt.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View arg0,boolean arg1) {
				if(arg1) {
					int year = Integer.parseInt(SystemDateTools.getYearFromDate());
					int month = Integer.parseInt(SystemDateTools.getMonthFromDate());
					int day = Integer.parseInt(SystemDateTools.getDayFromDate());
					DatePickerDialog datePickerLog = new DatePickerDialog(THISAC, new OnDateSetListener() {

						@Override
						public void onDateSet(DatePicker view,int year,int monthOfYear,
						        int dayOfMonth) {
							// TODO Auto-generated method stub
							Toast.makeText(THISAC, year + "year " + (monthOfYear + 1) + "month "
							        + dayOfMonth + "day", Toast.LENGTH_SHORT).show();

							datePickerEt.setText(year + "年 " + (monthOfYear + 1) + "月 "
							        + dayOfMonth + "日");
							datePickerEt.clearFocus();
							submitData = year + "-" + (monthOfYear + 1) + "-" + dayOfMonth;
						}
					}, year, month - 1, day);
					datePickerLog.show();
				}
			}
		});
		timePickerEt.setOnFocusChangeListener(new OnFocusChangeListener() {

			@Override
			public void onFocusChange(View arg0,boolean arg1) {
				if(arg1) {
					int hous = Integer.parseInt(SystemDateTools.getSystemHourOfTime());
					int minute = Integer.parseInt(SystemDateTools.getSystemMinuteOfTime());
					TimePickerDialog time = new TimePickerDialog(THISAC, new OnTimeSetListener() {

						@Override
						public void onTimeSet(TimePicker view,int hourOfDay,int minute) {
							// TODO Auto-generated method stub
							Toast.makeText(THISAC, hourOfDay + "hour " + minute + "minute", Toast.LENGTH_SHORT)
							        .show();
							timePickerEt.setText(hourOfDay + "时" + minute + "分");
							submitTime = hourOfDay + ":" + minute + ":00";
							timePickerEt.clearFocus();
						}
					}, hous, minute, true);
					time.show();
				}
			}
		});
		uploadIb = (ImageButton) findViewById(R.id.upload_ibutton);
		uploadIb.setOnClickListener(ocl);
	}

	private final NumberKeyListener	nkl	    = new NumberKeyListener() {

		                                        @Override
		                                        public int getInputType() {
			                                        // TODO Auto-generated method stub
			                                        return android.text.InputType.TYPE_CLASS_NUMBER;
		                                        }

		                                        @Override
		                                        protected char[] getAcceptedChars() {
			                                        // TODO Auto-generated method stub
			                                        return new char[]{'1', '2', '3', '4', '5', '6',
			'7', '8', '9', '0', '.'			    };
		                                        }
	                                        };

	private final OnClickListener	ocl	    = new OnClickListener() {

		                                        @Override
		                                        public void onClick(View arg0) {
			                                        switch (arg0.getId()) {
														case R.id.m_goback:
															Intent in = new Intent(THISAC, DischargeFinishListActivity.class);
															in.putExtra("initResult", spu
															        .getResponseResult());
															startActivity(in);
															break;
														case R.id.submit_button:
															progressDialog.setMessage("正在提交...");
															progressDialog.show();
															HashMap<String, String> map = new HashMap<String, String>();
															String followTaskId = getIntent()
															        .hasExtra("followId") == false ? "isNone"
															        : getIntent()
															                .getStringExtra("followId");
															map.put("taskId", followTaskId);
															map.put("time", (submitData
															        .equals("00") ? SystemDateTools
															        .getDateByNow() : submitData)
															        + " "
															        + (submitTime.equals("00") ? SystemDateTools
															                .getTimeByNow()
															                : submitTime));
															map.put("actual_amount", actualLoadCountEt
															        .getText().toString());
															JSONArray ja = new JSONArray();
															//
															JSONArray jsona = DBUtil
															        .selectPhotoRespondByTaskId(THISAC, followTaskId);
															if(jsona.length() > 0) {
																for(int idx = 0;idx < jsona
																        .length();idx++) {
																	try {
																		String responseId = jsona
																		        .getJSONObject(idx)
																		        .getString("RESPOND_ID");
																		ja.put(responseId);
																	} catch (JSONException e) {
																		e.printStackTrace();
																	}
																}
															}
															map.put("imgIds", ja.toString());
															new Thread(new BizNetworkService(THISAC, handlers, HttpActConstant.SUBMIT_ISCHARGE_FINISH_TASKS, map))
															        .start();
															break;
														case R.id.upload_ibutton:
															// Intent intent = new Intent(THISAC,
															// UploadPhotosListActivity.class);
															Intent intent = new Intent(THISAC, PublishedActivity.class);
															intent.putExtra("taskId", spu
															        .getFollowId());
															// 设置跳转标志
															spu.setFollowActivityName("DischargeFinishFormActivity");
															startActivity(intent);
															break;
														default:
															break;
													}
												}
	                                        };

	private final TextWatcher	    watcher	= new TextWatcher() {
		                                        String	outIndexBeforeCount;

		                                        @Override
		                                        public void onTextChanged(CharSequence arg0,
		                                                int arg1,int arg2,int arg3) {}

		                                        @Override
		                                        public void beforeTextChanged(CharSequence arg0,
		                                                int arg1,int arg2,int arg3) {
			                                        outIndexBeforeCount = actualLoadCountEt
			                                                .getText().toString();
		                                        }

		                                        @Override
		                                        public void afterTextChanged(Editable arg0) {
			                                        String getCount = getIntent()
			                                                .hasExtra("followCount") == false ? "0"
			                                                : getIntent()
			                                                        .getStringExtra("followCount");
			                                        String infoCount = actualLoadCountEt.getText()
			                                                .toString();
			                                        double d1 = Double.parseDouble(getCount);
			                                        double d2 = Double.parseDouble(infoCount);
			                                        double d3 = d1 - d2;
			                                        if(d3 < 0.0) {
				                                        actualLoadCountEt
				                                                .setText(outIndexBeforeCount);
				                                        actualLoadCountEt
				                                                .setSelection(outIndexBeforeCount
				                                                        .length() - 1);
			                                        } else {
				                                        DecimalFormat df1 = new DecimalFormat("0.00%");
				                                        String res = df1.format(d3 / d1);
				                                        cargoCountEt.setText(res);
				                                        String lossCountStr = "" + d3;
				                                        lossCountEt.setText(lossCountStr);
			                                        }
		                                        }
	                                        };

	private void initDatas() {
		try {
			String result = getIntent().hasExtra("followResult") == false ? "" : getIntent()
			        .getStringExtra("followResult");
			JSONArray getResult;
			getResult = new JSONArray(result.toString());
			System.out.println(getResult);
			getResult.getString(0);
			List<Map<String, Object>> mapList = new ArrayList<Map<String, Object>>();
			for(int i = 0;i < getResult.length();i++) {
				JSONObject o = new JSONObject(getResult.getString(i));
				if(o.has("records")) {
					String records = o.getString("records");
					JSONArray ja = new JSONArray(records.toString());
					int showListLenght = ja.length() > 5 ? 5 : ja.length();
					for(int j = 0;j < showListLenght;j++) {
						hasDatas = true;
						String MSG = ja.getJSONObject(j).has("MSG") == false ? "" : ja
						        .getJSONObject(j).getString("MSG");
						String TASKID = ja.getJSONObject(j).has("TASKID") == false ? "" : ja
						        .getJSONObject(j).getString("TASKID");
						String OPUSER = ja.getJSONObject(j).has("OPUSER") == false ? "" : ja
						        .getJSONObject(j).getString("OPUSER");
						String OPTIME = ja.getJSONObject(j).has("OPTIME") == false ? "" : ja
						        .getJSONObject(j).getString("OPTIME");
						String AURESULT = ja.getJSONObject(j).has("AURESULT") == false ? "" : ja
						        .getJSONObject(j).getString("AURESULT");
						Map<String, Object> map = new HashMap<String, Object>();
						map.put("msg", MSG);
						map.put("taskId", TASKID);
						map.put("opUser", OPUSER);
						map.put("opTime", OPTIME);
						map.put("auResult", AURESULT);
						mapList.add(map);
					}
				}
			}

			if(hasDatas) {
				recordList = (ListView) findViewById(R.id.record_list);
				// 生成动态数组，并且转入数据
				mData = mapList;
				// 生成适配器的ImageItem <====> 动态数组的元素，两者一一对应
				MyAdapter adapter = new MyAdapter(this);
				recordList.setAdapter(adapter);

			}

		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	public final class ViewHolder {
		public TextView		recordMsg, recordTime, recordMen;
		public LinearLayout	shipperItemLin;
	}

	public class MyAdapter extends BaseAdapter {

		private final LayoutInflater	mInflater;

		public MyAdapter(Context context) {
			this.mInflater = LayoutInflater.from(context);
		}

		@Override
		public int getCount() {
			// TODO Auto-generated method stub
			return mData.size();
		}

		@Override
		public Object getItem(int arg0) {
			// TODO Auto-generated method stub
			return null;
		}

		@Override
		public long getItemId(int arg0) {
			// TODO Auto-generated method stub
			return 0;
		}

		@SuppressLint({"NewApi", "ResourceAsColor" })
		@Override
		public View getView(final int position,View convertView,ViewGroup parent) {

			ViewHolder holder = null;

			holder = new ViewHolder();

			convertView = mInflater.inflate(R.layout.record_saggese_list_item, null);
			holder.recordMsg = (TextView) convertView.findViewById(R.id.record_msg);
			holder.recordTime = (TextView) convertView.findViewById(R.id.record_time);
			holder.recordMen = (TextView) convertView.findViewById(R.id.record_men);
			holder.shipperItemLin = (LinearLayout) convertView.findViewById(R.id.shipper_item_lin);
			convertView.setTag(holder);
			if(position % 2 == 1) {
				holder.shipperItemLin.setBackgroundColor(getResources()
				        .getColor(R.color.list_item_color1));
			} else {
				holder.shipperItemLin.setBackgroundColor(getResources()
				        .getColor(R.color.list_item_color));
			}
			holder.recordMsg.setText(mData.get(position).get("msg").toString());
			holder.recordTime.setText(mData.get(position).get("opTime").toString());
			holder.recordMen.setText(mData.get(position).get("opUser").toString());
			return convertView;
		}
	}

	public boolean onKeyDown(int keyCode,KeyEvent event) {

		if(keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
			// 这里重写返回键initResult
			Intent in = new Intent(THISAC, DischargeFinishListActivity.class);
			in.putExtra("initResult", spu.getResponseResult());
			startActivity(in);
			return true;
		}
		return false;

	}
}
